#include <iostream>
#include<vector>
#include<unistd.h>
#include<sys/types.h>
#include<sys/wait.h>
#include<stdio.h>
#include<stdlib.h>
typedef void (*hander_t)();  //hander_t = void(*)()

std::vector<hander_t> handlers; 

void fun_1()
{
  printf("work_1\n");
}
void fun_2()
{
  printf("work_2\n");
}

void Load()
{
  handlers.push_back(fun_1);
  handlers.push_back(fun_2);
}

int main()
{
  pid_t id = fork();
  if(id==0)
  {
    int cnt = 5;
    while(cnt--)
    {
      printf("I am child, my pid = %d, my ppid = %d, %d \n",getpid(),getppid(),
          cnt);
      sleep(1);
    }
    exit(11);
  }
  else
  {

    int quit = 0;
    while(1)
    {

      int status = 0;
      pid_t ret = waitpid(id,&status,WNOHANG);
      if(WIFEXITED(status))
      {
        printf("等待成功,退出码为:%d \n",WEXITSTATUS(status));
        quit = 1;
        break;
      }
      else{
          if(ret==0)
          {
            printf("子进程还没结束，我还得继续干活\n");
            if(handlers.empty()) Load();
            for(hander_t iter : handlers)
            {
              iter();
            }
          }
          if(ret<0)
          {
            printf("child running failed, signal = %d \n", status&&0x7f);
            quit = 1;
            break;
          }
      }
      sleep(1);
    }


 }
}
